package com.mar.meclient.bt.impl;

import java.io.IOException;
import java.io.OutputStream;

import net.java.dev.marge.entity.Device;

import com.mar.meclient.util.ByteBuffer;
/**
 * BTOutput stream for generic bt device 
 * TODO: avoid duplicated code!!! the same exists for server( for me there is no oficial byte buffer);
 * @author mar
 *
 */
class BTOutputStream extends OutputStream {


	
	private final Device btDevice;
	
	public BTOutputStream(Device clientDEvice){
		this.btDevice = clientDEvice;
	}
	
	private ByteBuffer buffer = ByteBuffer.wrap(new byte [ 1024 ] );
	
	public void write(int b) throws IOException {
		buffer.put((byte) b );
	}

	public void flush() throws IOException {
		buffer.flip();
		// extract data
		byte[] dataToSend = new byte[buffer.limit()];
		buffer.get( dataToSend);
		
		buffer.clear();		
		
		btDevice.send(dataToSend);
	}
	
/*	private byte[] buffer = new byte[1024];
	private int position = 0;
	public void write(int b) throws IOException {
		buffer[position++] = (byte)b;
	}
	
	public void write(byte[] b) throws IOException {
		write(b, 0, b.length);
	}
	
	public void write(byte[] b, int off, int len) throws IOException {
		for ( int i = off; i < len ; ++i ){
			buffer[position++] = b[i];
		}
	}
	
	public void flush(){
		btClientDevice.send( getBufferContent() );
		position = 0;
	}

	private byte[]  getBufferContent(){
		byte[] dataToSend = new byte[position];
		for ( int i = 0; i < position; i++ ){
			dataToSend[i] = buffer[i];
		}
		return dataToSend;
	}*/
	
	public void close(){
		btDevice.close();
	}
}
